package com.songcha.sakura.download

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import androidx.appcompat.app.AppCompatActivity
import com.songcha.library_common.util.ToastUtil
import com.songcha.sakura.MyApplication
import com.songcha.sakura.download.base.DownloadTask
import com.songcha.sakura.event.*
import com.songcha.sakura.service.DownloadService
import org.greenrobot.eventbus.EventBus

interface IServiceConnectionListener{
    fun onConnected()
    fun onDisConnected(){}
    //已和service建立消息连接
    fun onConnectInitialize()
}

//接收下载服务的消息
object DownloadServiceController {
    var url=""
    var thumb=""
    var fileName=""

    private var mConnectListener:IServiceConnectionListener?=null
    private var mServiceMessenger:Messenger?=null
    //bind时是否开启下载
    //private var mIsConnectDownload=true
    //判断是否超时
    //private var mReceiveTime=0L
    //private var mIsReceive=false
    //private var RECEIVE_TIMEOUT=60*3*1000L

    //private var mTimeOutObservable:Disposable?=null

    //private var mContext:Context?=null

    @JvmStatic
    fun isConnect():Boolean{
        return mServiceMessenger!=null
    }

    @JvmStatic
    fun bindService(listener: IServiceConnectionListener?){
        mConnectListener=listener
        com.songcha.sakura.MyApplication.getContext().bindService(
            Intent(com.songcha.sakura.MyApplication.getContext(), DownloadService::class.java),
            MyServiceConnection(),
            AppCompatActivity.BIND_AUTO_CREATE
        )

    }


    @JvmStatic
    fun createTask(url:String="",thumb:String="",fileName:String=""){
        this.url=url
        this.thumb=thumb
        this.fileName=fileName
        //this.mContext=context
        if(this.url.isNotEmpty()){
            val msg=Message.obtain()
            msg.replyTo=mClientMessenger
            msg.what=DownloadService.MSG_START_DOWNLOAD
            val bundle= Bundle()
            bundle.putString("url", this.url)
            bundle.putString("thumb", this.thumb)
            bundle.putString("fileName", this.fileName)
            msg.data=bundle

            mServiceMessenger!!.send(msg)

            this.url =""
            this.thumb =""
            this.fileName =""
        }

    }



    @JvmStatic
    fun pauseTask(task: DownloadTask){
        mServiceMessenger?.let {
            val msg=Message.obtain()
            msg.what=DownloadService.MSG_PAUSE_TASK
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)

        }
    }

    @JvmStatic
    fun resumeTask(task:DownloadTask){
        mServiceMessenger?.let {
            val msg=Message.obtain()
            msg.what=DownloadService.MSG_RESUME_TASK
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
    }

    @JvmStatic
    fun getLocalTaskList(){
        mServiceMessenger?.let {
            val msg=Message.obtain()
            msg.what=DownloadService.MSG_GET_LOCAL_TASK_LIST
            it.send(msg)
        }
    }

    @JvmStatic
    fun getTaskList(){
        mServiceMessenger?.let {
            val msg=Message.obtain()
            msg.what=DownloadService.MSG_GET_TASK_LIST
            it.send(msg)
        }
    }

    @JvmStatic
    fun cancelTask(url:String){
        mServiceMessenger?.let {
            val msg=Message.obtain()
            msg.what=DownloadService.MSG_CANCEL_TASK
            val bundle=Bundle()
            bundle.putString("url",url)
            msg.data=bundle
            it.send(msg)
        }
    }

    class MyServiceConnection:ServiceConnection{

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mServiceMessenger=Messenger(service)
            val msg=Message.obtain()
            msg.replyTo=mClientMessenger

            if(url.isNotEmpty()){
               // LogUtil.log("aaa","连接时下载")
                msg.what=DownloadService.MSG_START_DOWNLOAD
                val bundle= Bundle()
                bundle.putString("url",url)
                bundle.putString("thumb", thumb)
                bundle.putString("fileName", fileName)
                msg.data=bundle

                url=""
                thumb=""
                fileName=""

            }else{
                msg.what=DownloadService.MSG_CONNECT_INITIALIZE
            }

            mServiceMessenger?.send(msg)

            mConnectListener?.onConnected()

        }

        override fun onServiceDisconnected(name: ComponentName?) {
            ToastUtil.show("下载服务停止")
            mServiceMessenger=null
            EventBus.getDefault().postSticky(DownloadServiceDisconnectedEvent())

            mConnectListener?.onDisConnected()
        }

    }

    private val mHandler=object : Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            //LogUtil.log("aaa",msg.what)

            when(msg.what){
                DownloadService.MSG_DOWNLOAD_RET->{
                    if(msg.arg1>-1){
                        ToastUtil.show("已加入到下载队列")
                    }
                }
                DownloadService.MSG_CONNECT_INITIALIZE_RET->{
                    mConnectListener?.onConnectInitialize()
                }

                DownloadService.MSG_DOWNLOAD_INITIALIZE->{
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.INITIALIZE,task))

                }
                DownloadService.MSG_DOWNLOAD_START->{
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.START,task))
                }
                DownloadService.MSG_DOWNLOAD_UPDATE->{
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.UPDATE,task))

                    /*mTimeOutObservable=Observable.timer(RECEIVE_TIMEOUT,TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe {
                            if(!mIsReceive){
                                if(task!=null)
                                    EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.ERROR,task))
                                ToastUtil.show("下载超时")
                            }
                        }*/

                }
                DownloadService.MSG_DOWNLOAD_PAUSE->{
                    //mTimeOutObservable?.dispose()
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.PAUSE,task))
                }
                DownloadService.MSG_DOWNLOAD_COMPLETED->{
                    //mTimeOutObservable?.dispose()
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.COMPLETED,task))
                }
                DownloadService.MSG_DOWNLOAD_ERROR->{
                    //mTimeOutObservable?.dispose()
                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.ERROR,task))
                }
                DownloadService.MSG_CANCEL_TASK->{

                    val task=getMsgTask(msg)
                    if(task!=null)
                        EventBus.getDefault().postSticky(DownloadTaskEvent(DownloadTaskEventType.CANCEL,task))
                }
                DownloadService.MSG_RET_LOCAL_TASK_LIST->{
                    val bundle=msg.data
                    bundle.classLoader=DownloadServiceController::class.java.classLoader
                    val taskList=bundle.getParcelableArray("task_list")

                    if(taskList!=null && taskList.isNotEmpty()){
                        val list=mutableListOf<DownloadTask>()
                        for(task in taskList){
                            task as DownloadTask
                            list.add(task)
                        }
                        EventBus.getDefault().postSticky(LocalTaskListEvent(list))
                    }

                }

                DownloadService.MSG_RET_TASK_LIST->{
                    val bundle=msg.data
                    bundle.classLoader=DownloadServiceController::class.java.classLoader
                    val taskList=bundle.getParcelableArray("task_list")

                    if(taskList!=null && taskList.isNotEmpty()){
                        val list=mutableListOf<DownloadTask>()
                        for(task in taskList){
                            task as DownloadTask
                            list.add(task)
                        }
                        EventBus.getDefault().postSticky(TaskListEvent(list))
                    }

                }
            }
        }
    }

    private val mClientMessenger=Messenger(mHandler)

    fun getMsgTask(msg:Message):DownloadTask?{
        val bundle=msg.data
        bundle.classLoader=DownloadServiceController::class.java.classLoader
        val task=bundle.getParcelable<DownloadTask>("task")
        return task
    }

}